package com.coocaa.x.service.litecontent.providers.apps.controller;

import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.litecontent.providers.apps.data.AppStartTimesTableData;

import org.litepal.crud.DataSupport;

import java.util.HashMap;
import java.util.List;


public class AppStartTimesDataController {
    private static AppStartTimesDataController instance = null;

    public static AppStartTimesDataController getInstance() {
        if (instance == null) {
            instance = new AppStartTimesDataController();
        }
        return instance;
    }

    private AppStartTimesDataController() {

    }

    public void insert(String pkg) {
        List<AppStartTimesTableData> list = DataSupport.select("times")
                .where("pkgName = ?", pkg).find(AppStartTimesTableData.class);
        if (list != null && list.size() > 0) {
            LogUtils.d("base", "AppStartTimesDataController  insert  before size:" + list.size());
            AppStartTimesTableData data = new AppStartTimesTableData();
            data.setTimes(list.get(0).getTimes() + 1);
            data.updateAll("pkgName = ?", pkg);
        } else {
            LogUtils.d("base", "AppStartTimesDataController  first insert ");
            AppStartTimesTableData data = new AppStartTimesTableData();
            data.setPkgName(pkg);
            data.setTimes(1);
            data.save();
        }
    }

    public int getAppStartTimes(String pkg) {
        List<AppStartTimesTableData> list = DataSupport.where("pkgName = ?", pkg).find(
                AppStartTimesTableData.class);
        if (list != null && list.size() > 0) {
            int count = list.get(0).getTimes();
            LogUtils.d("base", "getAppStartTimes  count: " + count);
            return count;
        }
        LogUtils.d("base", "getAppStartTimes  count:0 ");
        return 0;
    }

    public HashMap<String, Integer> getAllAppStartTimesMap() {
        List<AppStartTimesTableData> list = DataSupport.findAll(AppStartTimesTableData.class);
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        for (AppStartTimesTableData data : list) {
            map.put(data.getPkgName(), data.getTimes());
        }
        LogUtils.d("app", "getAllAppStartTimesMap  size:" + map.size());
        return map;
    }

}
